﻿using System;
using System.Configuration;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;
using Common.Logging;
using In.Api.Dto.HisWs;
using Newtonsoft.Json;
using OutDbContext;
using User.Api.BizExtensions;
using User.Api.Dto.Card;
using User.Api.Helpers;
using User.Api.HttpClients;

namespace User.Api.Controllers
{
    public class CardController : ApiController
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(CardController));
        private FsssdqfybjyEntities _ctx;

        protected override void Initialize(HttpControllerContext controllerContext)
        {
            _ctx = new FsssdqfybjyEntities();
            base.Initialize(controllerContext);
        }

        protected override void Dispose(bool disposing)
        {
            _ctx.Dispose();
            base.Dispose(disposing);
        }

        /// <summary>
        /// 获取用户的所有诊疗号
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetAll")]
        public GetAllResponse GetAll()
        {
            var azUser = AzUser.GetInApi(Request);
            //之前的查询会发生死锁，优化查询为NoLock
            var dbCards = (_ctx.HospCards.Where(x => x.WxUserId == azUser.UserId && x.RecStatus == 1)
                .OrderByDescending(x => x.IsDefault).ThenBy(x => x.CardNo)
                .Select(x => new
                {
                    Id = x.Id,
                    x.CardType,
                    x.CardNo,
                    x.Name,
                    x.IsDefault
                })).ToListReadUncommitted();

            var cards = dbCards.Select(x => new GetAllResponse.Card
            {
                Id = x.Id,
                Type = HospCardExtensions.ToCardTypeName(x.CardType),
                Num = x.CardNo,
                Name = x.Name,
                IsDefault = x.IsDefault == 1
            }).ToList();

            return new GetAllResponse
            {
                ResultCode = "0",
                ResultMsg = "",
                Cards = cards
            };
        }

        /// <summary>
        /// 设置默认诊疗号
        /// </summary>
        /// <param name="id">诊疗号id</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("SetDefault")]
        public SetDefaultResponse SetDefault(long id)
        {
            var azUser = AzUser.GetInApi(Request);

            var cards = _ctx.HospCards.Where(x => x.WxUserId == azUser.UserId).ToList();
            foreach (var card in cards)
            {
                card.IsDefault = 0;
                if (card.Id == id)
                {
                    card.IsDefault = 1;
                }
            }
            _ctx.SaveChanges();

            return new SetDefaultResponse { ResultCode = "0", ResultMsg = "" };
        }

        /// <summary>
        /// 删除诊疗号
        /// </summary>
        /// <param name="id">诊疗号id</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("Delete")]
        public DeleteResponse Delete(int id)
        {
            var azUser = AzUser.GetInApi(Request);

            var card = _ctx.HospCards.FirstOrDefault(x => x.Id == id && x.WxUserId == azUser.UserId);
            if (card != null)
            {
                card.RecStatus = 2;
                card.RecDeleteDt = DateTime.Now;
                _ctx.SaveChanges();

                // 如果删除了默认卡，则自动设置其余诊疗号小的卡为默认诊疗号
                if (card.IsDefault == 1)
                {
                    var cards = _ctx.HospCards.Where(x => x.RecStatus == 1 && x.WxUserId == azUser.UserId)
                        .OrderBy(x => x.CardNo).ToList();
                    for (int i = 0; i < cards.Count; i++)
                    {
                        cards[i].IsDefault = i == 0 ? 1 : 0;
                    }
                    _ctx.SaveChanges();
                }
            }

            return new DeleteResponse { ResultCode = "0", ResultMsg = "" };
        }

        /// <summary>
        /// 绑定诊疗号
        /// </summary>
        /// <param name="isDefault">是否设置为默认诊疗号</param>
        /// <param name="type">卡类型</param>
        /// <param name="num">诊疗号</param>
        /// <param name="name">姓名</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("AddBinding")]
        public AddBindingResponse AddBinding(bool isDefault, int type, string num, string name)
        {
            var azUser = AzUser.GetInApi(Request);

            var cardMax = ConfigurationManager.AppSettings["CardMax"].ToInt32();
            var cardCount = _ctx.HospCards
                .Count(x => x.WxUserId == azUser.UserId && x.RecStatus == 1);
            if (cardCount >= cardMax)
            {
                return new AddBindingResponse
                {
                    ResultCode = "1",
                    ResultMsg = "最多可以添加" + cardMax + "个诊疗号!"
                };
            }

            if (cardCount == 0)
            {
                isDefault = true;
            }

            var existCard =
                _ctx.HospCards.FirstOrDefault(x => x.RecStatus == 1 && x.CardNo == num && x.WxUserId == azUser.UserId);
            if (existCard != null)
            {
                return new AddBindingResponse
                {
                    ResultCode = "2",
                    ResultMsg = "您已添加过该诊疗号!"
                };
            }

            // 获取院内诊疗号信息
            var request = new Request4GetPatientInfo();
            request.CardNo = num;

            Response4GetPatientInfo response;
            try
            {
                var httpClient = InHttpClient.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("HisWs/GetPatientInfo", request).Result;
                responseMsg.EnsureSuccessStatusCode();
                response = responseMsg.Content.ReadAsAsync<Response4GetPatientInfo>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用院内获取病人信息Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                return new AddBindingResponse
                {
                    ResultCode = "3",
                    ResultMsg = "操作失败，获取诊疗号信息超时"
                };
            }

            if (response.ResultCode != "0")
            {
                return new AddBindingResponse
                {
                    ResultCode = "4",
                    ResultMsg = response.ResultDesc
                };
            }

            if (response.PatientInfo.Name.Trim() != name.Trim())
            {
                return new AddBindingResponse
                {
                    ResultCode = "2",
                    ResultMsg = "操作失败，诊疗号与姓名不匹配"
                };
            }

            var newCard = new HospCard
            {
                WxUserId = azUser.UserId,
                CardType = 0,
                CardNo = num.Trim(),
                PatientName = response.PatientInfo.Name.Trim(),
                RecStatus = 1,
                RecCreateDt = DateTime.Now,
                RecUpdateDt = DateTime.Now,
                PatientId = response.PatientInfo.PatientId.Trim(),
                InDeptNo = response.PatientInfo.InDeptNo.Trim(),
                Name = response.PatientInfo.Name.Trim(),
                Gender = response.PatientInfo.Gender.Trim(),
                Age = response.PatientInfo.Age.Trim(),
                Birthdate = response.PatientInfo.Birthdate.Trim(),
                IdenNo = response.PatientInfo.IdenNo.Trim(),
                Phone = response.PatientInfo.Phone.Trim(),
                FeeType = response.PatientInfo.FeeType.Trim()
            };

            _ctx.HospCards.Add(newCard);
            _ctx.SaveChanges();

            var existsCards = _ctx.HospCards.Where(x => x.CardNo == newCard.CardNo);
            foreach (var existsCard in existsCards)
            {
                existsCard.RecUpdateDt = DateTime.Now;
                existsCard.PatientName = newCard.PatientName;
                existsCard.PatientId = newCard.PatientId;
                existsCard.InDeptNo = newCard.InDeptNo;
                existsCard.Name = newCard.Name;
                existsCard.Gender = newCard.Gender;
                existsCard.Age = newCard.Age;
                existsCard.Birthdate = newCard.Birthdate;
                existsCard.IdenNo = newCard.IdenNo;
                existsCard.Phone = newCard.Phone;
                existsCard.FeeType = newCard.FeeType;
            }
            _ctx.SaveChanges();

            if (isDefault)
            {
                SetDefault(newCard.Id);
            }

            return new AddBindingResponse
            {
                ResultCode = "0",
                ResultMsg = "",
                Id = newCard.Id,
                Type = HospCardExtensions.ToCardTypeName(newCard.CardType),
                Num = newCard.CardNo,
                Name = newCard.PatientName,
                IsDefault = newCard.IsDefault == 1,
                IsSelected = false
            };
        }

        /// <summary>
        /// 创建虚拟诊疗号
        /// </summary>
        /// <param name="name">姓名</param>
        /// <param name="certNo">身份证号码</param>
        /// <param name="phone">联系电话</param>
        /// <param name="address">住址</param>
        /// <param name="isDefault">是否设置为默认诊疗号</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("AddNew")]
        public AddNewResponse AddNew(string name, string certNo, string phone, string address, string provinceCode, string provinceName, string cityCode, string cityName, string townCode, string townName, string districtCode, string districtName, bool isDefault)
        {
            Logger.ErrorFormat("调用院内创建诊疗号Api出错,信息：{0},{1},{2},{3},{4}", provinceName, cityName, districtName, townName, address);
            Logger.ErrorFormat("调用院内创建诊疗号Api出错,信息：{0},{1},{2},{3},{4}", provinceCode, cityCode, districtCode, townCode, address);
            var azUser = AzUser.GetInApi(Request);

            var cardMax = ConfigurationManager.AppSettings["CardMax"].ToInt32();
            var cardCount = _ctx.HospCards
                .Count(x => x.WxUserId == azUser.UserId && x.RecStatus == 1);
            if (cardCount >= cardMax)
            {
                return new AddNewResponse
                {
                    ResultCode = "1",
                    ResultMsg = "最多可以添加" + cardMax + "个诊疗号!"
                };
            }

            if (cardCount == 0)
            {
                isDefault = true;
            }

            var existCard =
                _ctx.HospCards.FirstOrDefault(x => x.RecStatus == 1 && x.Name == name && x.IdenNo == certNo && x.WxUserId == azUser.UserId);
            if (existCard != null)
            {
                return new AddNewResponse
                {
                    ResultCode = "2",
                    ResultMsg = "您已添加过该身份证!"
                };
            }

            DateTime birthDt;
            string sex;
            var isValidCertNo = HospCardExtensions.IsValidCertNo(certNo, out birthDt, out sex);
            if (!isValidCertNo)
            {
                return new AddNewResponse
                {
                    ResultCode = "2",
                    ResultMsg = "无效的身份证号码"
                };
            }

            #region 通过身份证查询HIS中是否有诊疗号

            var request4GetClinPatient = new Request4GetClinPatient();
            request4GetClinPatient.IdCard = certNo;
            Response4GetClinPatient response4GetClinPatient;
            try
            {
                var httpClient = InHttpClient.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("HisWs/GetClinPatient", request4GetClinPatient).Result;
                responseMsg.EnsureSuccessStatusCode();
                response4GetClinPatient = responseMsg.Content.ReadAsAsync<Response4GetClinPatient>().Result;
            }
            catch (Exception ex)
            {
                return new AddNewResponse
                {
                    ResultCode = "3",
                    ResultMsg = "操作失败，创建诊疗号超时"
                };
            }

            //如果成功则返回
            if (response4GetClinPatient.ResultCode == "0")
            {
                if (response4GetClinPatient.ClinPatientInfo != null && response4GetClinPatient.ClinPatientInfo.CardNo != null)
                {
                    using (var ctx = new FsssdqfybjyEntities())
                    {
                        var patient = response4GetClinPatient.ClinPatientInfo;
                        var card = ctx.HospCards.FirstOrDefault(x => x.CardType == 0 && x.CardNo.Trim() == patient.CardNo.Trim()
                                    && x.PatientName.Trim() == name.Trim()
                                    && x.WxUserId == azUser.UserId);

                        if (card != null)
                        {
                            if (card.RecStatus == 1)
                            {
                                return new AddNewResponse
                                {
                                    ResultCode = "3",
                                    ResultMsg = "您已建诊疗号且已绑定该诊疗号"
                                };
                            }
                            else
                            {
                                card.RecStatus = 1;
                                card.RecUpdateDt = System.DateTime.Now;
                                card.RecDeleteDt = null;
                                ctx.SaveChanges();

                                return new AddNewResponse
                                {
                                    ResultCode = "3",
                                    ResultMsg = "您已建诊疗号，绑定诊疗号成功"
                                };
                            }
                        }
                        if (name.ToUpper() == patient.Name.ToUpper())
                        {
                            //处理数据库记录
                            var model = new HospCard
                            {
                                WxUserId = azUser.UserId,
                                CardType = 0,
                                CardNo = patient.CardNo,
                                PatientName = name.Trim(),
                                RecStatus = 1,
                                RecCreateDt = DateTime.Now,
                                RecUpdateDt = DateTime.Now,
                                PatientId = patient.HosPatId,
                                InDeptNo = "",
                                Name = patient.Name,
                                Gender = patient.Sex,
                                Age = "",
                                Birthdate = patient.BirthDay,
                                IdenNo = patient.IdCard,
                                Phone = patient.Phone,
                                FeeType = patient.PayType
                            };
                            ctx.HospCards.Add(model);
                            ctx.SaveChanges();

                            return new AddNewResponse
                            {
                                ResultCode = "3",
                                ResultMsg = "您已建诊疗号，绑定诊疗号成功"
                            };
                        }
                        else//姓名对不上
                        {
                            return new AddNewResponse
                            {
                                ResultCode = "3",
                                ResultMsg = "您的身份证号已经被登记，请校对您的姓名"
                            };
                        }
                    }
                }
            }
            #endregion

            // 创建诊疗号
            var createCardRequest = new Request4NewClinPatient();
            createCardRequest.IdCard = certNo;
            createCardRequest.PatientName = name;
            createCardRequest.BirthDay = birthDt.ToString("yyyy-MM-dd");
            createCardRequest.Sex = sex;
            createCardRequest.Phone = phone;
            createCardRequest.DETAIL_ADDRESS = address;
            createCardRequest.PROVINCE_CODE = provinceCode;
            createCardRequest.PROVINCE_NAME = provinceName;
            createCardRequest.CITY_CODE = cityCode;
            createCardRequest.CITY_NAME = cityName;
            createCardRequest.TOWN_CODE = townCode;
            createCardRequest.TOWN_NAME = townName;
            createCardRequest.RIGION_CODE = districtCode;
            createCardRequest.REGION_NAME = districtName;

            Response4NewClinPatient createCardResponse;
            try
            {
                var httpClient = InHttpClient.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("HisWs/NewClinPatient", createCardRequest).Result;
                responseMsg.EnsureSuccessStatusCode();
                createCardResponse = responseMsg.Content.ReadAsAsync<Response4NewClinPatient>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用院内创建诊疗号Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                return new AddNewResponse
                {
                    ResultCode = "3",
                    ResultMsg = "操作失败，创建诊疗号超时"
                };
            }

            if (createCardResponse.ResultCode != "0")
            {
                return new AddNewResponse
                {
                    ResultCode = "4",
                    ResultMsg = createCardResponse.ResultDesc
                };
            }

            // 获取院内诊疗号信息
            var getPatientRequest = new Request4GetPatientInfo();
            getPatientRequest.CardNo = createCardResponse.CardNo;

            Response4GetPatientInfo getPatientResponse;
            try
            {
                var httpClient = InHttpClient.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("HisWs/GetPatientInfo", getPatientRequest).Result;
                responseMsg.EnsureSuccessStatusCode();
                getPatientResponse = responseMsg.Content.ReadAsAsync<Response4GetPatientInfo>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用院内获取病人信息Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                return new AddNewResponse
                {
                    ResultCode = "5",
                    ResultMsg = "操作失败，获取诊疗号信息超时"
                };
            }

            if (getPatientResponse.ResultCode != "0")
            {
                return new AddNewResponse
                {
                    ResultCode = "6",
                    ResultMsg = getPatientResponse.ResultDesc
                };
            }

            var newCard = new HospCard
            {
                WxUserId = azUser.UserId,
                CardType = 0,
                CardNo = createCardResponse.CardNo,
                PatientName = getPatientResponse.PatientInfo.Name.Trim(),
                RecStatus = 1,
                RecCreateDt = DateTime.Now,
                RecUpdateDt = DateTime.Now,
                PatientId = getPatientResponse.PatientInfo.PatientId.Trim(),
                InDeptNo = getPatientResponse.PatientInfo.InDeptNo.Trim(),
                Name = getPatientResponse.PatientInfo.Name.Trim(),
                Gender = getPatientResponse.PatientInfo.Gender.Trim(),
                Age = getPatientResponse.PatientInfo.Age.Trim(),
                Birthdate = getPatientResponse.PatientInfo.Birthdate.Trim(),
                IdenNo = getPatientResponse.PatientInfo.IdenNo.Trim(),
                Phone = getPatientResponse.PatientInfo.Phone.Trim(),
                FeeType = getPatientResponse.PatientInfo.FeeType.Trim()
            };

            _ctx.HospCards.Add(newCard);
            _ctx.SaveChanges();

            var existsCards = _ctx.HospCards.Where(x => x.CardNo == newCard.CardNo);
            foreach (var existsCard in existsCards)
            {
                existsCard.RecUpdateDt = DateTime.Now;
                existsCard.PatientName = newCard.PatientName;
                existsCard.PatientId = newCard.PatientId;
                existsCard.InDeptNo = newCard.InDeptNo;
                existsCard.Name = newCard.Name;
                existsCard.Gender = newCard.Gender;
                existsCard.Age = newCard.Age;
                existsCard.Birthdate = newCard.Birthdate;
                existsCard.IdenNo = newCard.IdenNo;
                existsCard.Phone = newCard.Phone;
                existsCard.FeeType = newCard.FeeType;
            }
            _ctx.SaveChanges();

            if (isDefault)
            {
                SetDefault(newCard.Id);
            }

            return new AddNewResponse
            {
                ResultCode = "0",
                ResultMsg = "",
                Id = newCard.Id,
                Type = HospCardExtensions.ToCardTypeName(newCard.CardType),
                Num = newCard.CardNo,
                Name = newCard.PatientName,
                IsDefault = newCard.IsDefault == 1,
                IsSelected = false
            };
        }
        /// <summary>
        /// 省
        /// </summary>
        /// 
        [HttpGet]
        [ActionName("GetPROVINCEInfo")]
        public GetPROVINCEInfoResponse GetPROVINCEInfo()
        {
            Response4GetPROVINCE resp;
            try
            {
                var httpClient = InHttpClient.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("HisWs/GetPROVINCE", "").Result;
                responseMsg.EnsureSuccessStatusCode();
                resp = responseMsg.Content.ReadAsAsync<Response4GetPROVINCE>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用 GetPROVINCE Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                return new GetPROVINCEInfoResponse
                {
                    ResultCode = "3",
                    ResultMsg = "服务器或网络异常，请联系客服"
                };
            }
            if (resp.ResultCode != "0")
            {
                return new GetPROVINCEInfoResponse
                {
                    ResultCode = "4",
                    ResultMsg = resp.ResultDesc
                };
            }

            return new GetPROVINCEInfoResponse
            {
                ResultCode = "0",
                ResultMsg = "",
                CITYList = resp.ResultList.Select(x => new GetPROVINCEInfoResponse.CITY
                {
                    CODE = x.PROVINCE_CODE, //DepartExtensions.ToBranchName(x.BranchNo),
                    NAME = x.PROVINCE_NAME
                }).ToList()
            };
        }
        /// <summary>
        /// 市
        /// </summary>
        /// 
        [HttpGet]
        [ActionName("GetCityInfo")]
        public GetPROVINCEInfoResponse GetCityInfo(string code)
        {
            if (code == "-1")
            {
                return new GetPROVINCEInfoResponse
                {
                    ResultCode = "1",
                    ResultMsg = "请重新选择",
                };
            }
            var req = new Request4GetCity();
            req.PROVINCE_CODE = code;

            Response4GetCity resp;
            try
            {
                var httpClient = InHttpClient.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("HisWs/GetCity", req).Result;
                responseMsg.EnsureSuccessStatusCode();
                resp = responseMsg.Content.ReadAsAsync<Response4GetCity>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用 GetCity Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                return new GetPROVINCEInfoResponse
                {
                    ResultCode = "3",
                    ResultMsg = "服务器或网络异常，请联系客服"
                };
            }
            if (resp.ResultCode != "0")
            {
                return new GetPROVINCEInfoResponse
                {
                    ResultCode = "4",
                    ResultMsg = resp.ResultDesc
                };
            }

            return new GetPROVINCEInfoResponse
            {
                ResultCode = "0",
                ResultMsg = "",
                CITYList = resp.CITYList.Select(x => new GetPROVINCEInfoResponse.CITY
                {
                    CODE = x.CITY_CODE, //DepartExtensions.ToBranchName(x.BranchNo),
                    NAME = x.CITY_NAME
                }).ToList()
            };
        }
        /// <summary>
        /// 县区
        /// </summary>
        /// 
        [HttpGet]
        [ActionName("GetDistrictInfo")]
        public GetPROVINCEInfoResponse GetDistrictInfo(string code)
        {
            if (code == "-1")
            {
                return new GetPROVINCEInfoResponse
                {
                    ResultCode = "1",
                    ResultMsg = "请重新选择",
                };
            }
            var req = new Request4GetDistrict();
            req.CITY_CODE = code;
            Response4GetDistrict response4GetPROVINCE;
            try
            {
                var httpClient = InHttpClient.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("HisWs/GetDistrict", req).Result;
                responseMsg.EnsureSuccessStatusCode();
                response4GetPROVINCE = responseMsg.Content.ReadAsAsync<Response4GetDistrict>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用 GetDistrict Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                return new GetPROVINCEInfoResponse
                {
                    ResultCode = "3",
                    ResultMsg = "服务器或网络异常，请联系客服"
                };
            }
            if (response4GetPROVINCE.ResultCode != "0")
            {
                return new GetPROVINCEInfoResponse
                {
                    ResultCode = "4",
                    ResultMsg = response4GetPROVINCE.ResultDesc
                };
            }

            return new GetPROVINCEInfoResponse
            {
                ResultCode = "0",
                ResultMsg = "",
                CITYList = response4GetPROVINCE.DISTRICTList.Select(x => new GetPROVINCEInfoResponse.CITY
                {
                    CODE = x.DISTRICT_CODE, //DepartExtensions.ToBranchName(x.BranchNo),
                    NAME = x.DISTRICT_NAME
                }).ToList()
            };
        }

        /// <summary>
        /// 街道
        /// </summary>
        /// 
        [HttpGet]
        [ActionName("GetTOWNInfo")]
        public GetPROVINCEInfoResponse GetTOWNInfo(string code)
        {
            if (code == "-1")
            {
                return new GetPROVINCEInfoResponse
                {
                    ResultCode = "1",
                    ResultMsg = "请重新选择",
                };
            }
            var req = new Request4GetDistrict();
            req.CITY_CODE = code;
            Response4GetDistrict response4GetPROVINCE;
            try
            {
                var httpClient = InHttpClient.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("HisWs/GetTOWN", req).Result;
                responseMsg.EnsureSuccessStatusCode();
                response4GetPROVINCE = responseMsg.Content.ReadAsAsync<Response4GetDistrict>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用 GetDistrict Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                return new GetPROVINCEInfoResponse
                {
                    ResultCode = "3",
                    ResultMsg = "服务器或网络异常，请联系客服"
                };
            }
            if (response4GetPROVINCE.ResultCode != "0")
            {
                return new GetPROVINCEInfoResponse
                {
                    ResultCode = "4",
                    ResultMsg = response4GetPROVINCE.ResultDesc
                };
            }

            return new GetPROVINCEInfoResponse
            {
                ResultCode = "0",
                ResultMsg = "",
                CITYList = response4GetPROVINCE.DISTRICTList.Select(x => new GetPROVINCEInfoResponse.CITY
                {
                    CODE = x.DISTRICT_CODE, //DepartExtensions.ToBranchName(x.BranchNo),
                    NAME = x.DISTRICT_NAME
                }).ToList()
            };
        }
        /// <summary>
        /// 获取门诊病人信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetClinPatientInfo")]
        public GetClinPatientInfoResponse GetClinPatientInfo(string cardNo)
        {
            //获取门诊病人信息
            var request4GetClinPatient = new Request4GetClinPatient();
            request4GetClinPatient.CardNo = cardNo;

            Response4GetClinPatient response4GetClinPatient;
            try
            {
                var httpClient = InHttpClient.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("HisWs/GetClinPatient", request4GetClinPatient).Result;
                responseMsg.EnsureSuccessStatusCode();
                response4GetClinPatient = responseMsg.Content.ReadAsAsync<Response4GetClinPatient>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用GetClinPatient Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                return new GetClinPatientInfoResponse
                {
                    ResultCode = "3",
                    ResultMsg = "服务器或网络异常，请联系客服"
                };
            }

            if (response4GetClinPatient.ResultCode != "0")
            {
                return new GetClinPatientInfoResponse
                {
                    ResultCode = "4",
                    ResultMsg = response4GetClinPatient.ResultDesc
                };
            }
            var responseClinPatientInfo = response4GetClinPatient.ClinPatientInfo;
            var clinPatientInfo = new GetClinPatientInfoResponse.ClinPatient()
            {
                HosPatId = responseClinPatientInfo.HosPatId,
                Sex = responseClinPatientInfo.Sex,
                BirthDay = responseClinPatientInfo.BirthDay,
                IdCard = responseClinPatientInfo.IdCard,
                FamilyAddress = responseClinPatientInfo.FamilyAddress,
                Phone = responseClinPatientInfo.Phone,
                FamilyPhone = responseClinPatientInfo.FamilyPhone,
                ClinNo = responseClinPatientInfo.ClinNo,
                CardNo = responseClinPatientInfo.CardNo,
                PayType = responseClinPatientInfo.PayType,
                PactCode = responseClinPatientInfo.PactCode
            };

            return new GetClinPatientInfoResponse()
            {
                ResultCode = "0",
                ResultMsg = "",
                ClinPatientInfo = clinPatientInfo
            };
        }

        /// <summary>
        /// 获取产妇信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetMaternalInfo")]
        public GetMaternalInfoResponse GetMaternalInfo(string cardNo, string IDCard)
        {
            //获取产妇信息
            var request4GetMaternal = new Request4GetMaternalInfo();
            request4GetMaternal.WardNo = cardNo;
            request4GetMaternal.IDCard = IDCard;

            Response4GetMaternalInfo response4GetMaternal;
            try
            {
                var httpClient = InHttpClient.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("HisWs/GetMaternalInfo", request4GetMaternal).Result;
                responseMsg.EnsureSuccessStatusCode();
                response4GetMaternal = responseMsg.Content.ReadAsAsync<Response4GetMaternalInfo>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("获取GetMaternalInfo Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                return new GetMaternalInfoResponse
                {
                    ResultCode = "3",
                    ResultMsg = "服务器或网络异常，请联系客服"
                };
            }

            if (response4GetMaternal.ResultCode != "0")
            {
                return new GetMaternalInfoResponse
                {
                    ResultCode = "4",
                    ResultMsg = response4GetMaternal.ResultDesc
                };
            }
            var responseMaternalInfo = response4GetMaternal.MaternalInfo;
            var MaternalInfo = new GetMaternalInfoResponse.MaternalList()
            {
                Name = responseMaternalInfo.Name,
                Age = responseMaternalInfo.Age,
                IDCard = responseMaternalInfo.IDCard,
                CardNo = responseMaternalInfo.CardNo,
                PregnancyDT = responseMaternalInfo.PregnancyDT,
                ChildbirthDT = responseMaternalInfo.ChildbirthDT
            };

            return new GetMaternalInfoResponse()
            {
                ResultCode = "0",
                ResultMsg = "",
                ClinPatientInfo = MaternalInfo
            };
        }
    }
}
